package mediaServer.logic;

import java.io.IOException;
import java.util.ArrayList;

import mediaServer.configurationManagement.Configuration;

/**
 * This class controls the instance of the VLC used for streaming
 * @author GelidElf
 *
 */
public class VLCManager implements MediaManagerInterface{

	private Configuration _config = null;
	private String _media = null;
	private ArrayList <String> _addresses = null;
	private ArrayList <Integer> _ports = null;
	private String _vlcPath = null;
	private String[] args = { _vlcPath, "-vvv",_media ,""};


	public VLCManager(Configuration config) {
		_addresses = new ArrayList<String>();
		_ports = new ArrayList<Integer>();
		_config = config;
		_media = _config.get_mediaFile().getAbsolutePath().toString();
		_vlcPath = _config.get_vlcPath();
		args[0] = _vlcPath;
		args[2] = _media;
	}
	
	public void addAddress(String add, int port){
		_addresses.add(add);
		_ports.add(new Integer(port));
	}
	
	public void removeAddress (String add, int port){
		for (int i = 0; i < _addresses.size(); i++) {
			if ((_addresses.get(i).equals(add)) && (_ports.get(i) == port)){
				_addresses.remove(i);
				_ports.remove(i);
			}
		}
	}

	public void transmit() {
		// TODO Auto-generated method stub
		args[args.length-1] = generate();
        try {
            Runtime.getRuntime().exec(args[0] + " " + args[1] + " " + args[2] + " " + args[3] );
        } catch (IOException ioe) {
            System.err.println("IO exception: " + ioe.getMessage());
        }
	}
	
	private String generate (){
		String start = null;
		String end = null;
		String finish = null;
		if ( _addresses.size() == 1){
			start = "--sout='#";
			end = "'";
		}
		else if (_addresses.size() >1 ){
			start = "--sout='#duplicate{";
			end = "}'";
		}
		finish = start;
		for (int i = 0; i < _addresses.size(); i++) {
			finish = finish + generateString(i); 
		}
		finish = finish +end;
		return finish;
	}
	
	private String generateString(int i){
		//" ,name=\""+ _config.get_mediaName()+"\
		return "rtp{dst=" + _addresses.get(i) +",port=" +_ports.get(i)+ ",mux=ts}";
	}
	
	
	
}
